import {
  createSlice,
  createAction,
  PayloadAction,
  createAsyncThunk,
} from "@reduxjs/toolkit";
import { ProductDetailData } from "../../Utils/Http";
interface productState {
  error: string | null;
  loading: boolean;
  data: any;
}

// 初始状态
const initialState: productState = {
  error: null,
  loading: true,
  data: null,
};

// 创建即将派发的Action type
const fetchStart = createAction("fetchStart");
const fetchSuccess = createAction("fetchSuccess");
const fetchFail = createAction("fetchFail");

// 使用createAsyncThunk创建异步action
export const getProductDetail = createAsyncThunk(
  "productDetail/getProductDetail",
  async (id: string, thunkAPI) => {
    // thunkAPI.dispatch(productDetailSlice.actions.fetchStart());
    // try {
    //   const res = await ProductDetailData(id);
    //   thunkAPI.dispatch(productDetailSlice.actions.fetchSuccess(res));
    // } catch (error) {
    //   thunkAPI.dispatch(productDetailSlice.actions.fetchFail(error.data));
    // }
    return await ProductDetailData(id);
  }
);

export const productDetailSlice = createSlice({
  name: "productDetail", // 切片的命名空间
  initialState, //状态
  reducers: {
    //此处的reducer隐式结合redux的action和reducer，底层会重构state状态，更新数据
    // fetchStart对应的处理函数则是真正的reducer，参数state则是当前store数据
    [fetchStart.type]: (state) => {
      state.loading = true;
    },
    [fetchSuccess.type]: (state, action) => {
      state.loading = false;
      state.data = action.payload;
    },
    [fetchFail.type]: (state, action: PayloadAction<string>) => {
      state.loading = false;
      state.error = action.payload;
    },
  },
  // 处理RTK异步createAsyncThunk
  extraReducers: {
    [getProductDetail.pending.type]: (state) => {
      state.loading = true;
    },
    [getProductDetail.fulfilled.type]: (state, action) => {
      state.loading = false;
      state.error = null;
      state.data = action.payload;
    },
    [getProductDetail.rejected.type]: (
      state,
      action: PayloadAction<string | null>
    ) => {
      state.loading = false;
      state.error = action.payload;
    },
  },
});
